package cn.dvptech.remotecontrol.screenmirror.sender;

import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

import timber.log.Timber;

/**
 *    author  : ulongx
 *    website : www.dvptech.cn
 *    date    : 2024/7/20
 *    desc    :
 */
public class TcpReadThread extends Thread {
    private final static String TAG = "TcpReadThread";
    private BufferedInputStream bis;
    private OnTcpReadListener mListener;
    private volatile boolean isRunning;
//    private InputStream inputStream;

    public TcpReadThread(BufferedInputStream bis, OnTcpReadListener listener) {
        this.bis = bis;
        this.mListener = listener;
        isRunning = true;
    }

    @Override
    public void run() {
        super.run();
        try {
            while (isRunning) {
                acceptMsg();
            }
        } catch (IOException e) {
            isRunning = false;
            mListener.socketDisconnect();
//                Log.e(TAG, "read data Exception = " + e.toString());
        }
    }

    public void shutDown() {
        isRunning = false;
        this.interrupt();
    }

    public void acceptMsg() throws IOException {
        if (mListener == null) {
            return;
        }
        if (bis.available() <= 0) {
            return;
        }
        byte[] bytes = new byte[2];
        bis.read(bytes);
        String s = new String(bytes);
        if (TextUtils.isEmpty(s)) {
            return;
        }
        if (TextUtils.equals(s, "OK")) {
            mListener.connectSuccess();
            return;
        }

        byte[] length = readBytes(bis, 4);
        int lengthInt = bytesToInt(length);
        byte[] data = readBytes(bis, lengthInt);

        Timber.i("acceptMsg:%s", new String(data));
        //服务端发过来数据
        mListener.onReceiveMessage(new String(data));
    }

    /**
     * 保证从流里读到指定长度数据
     *
     * @param is
     * @param readSize
     * @return
     * @throws Exception
     */
    private byte[] readBytes(InputStream is, int readSize) throws IOException {
        ByteArrayOutputStream baoS = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024]; // 使用一个合理大小的缓冲区
        int bytesRead;
        int totalBytesRead = 0;

        while (totalBytesRead < readSize &&
                (bytesRead = is.read(buffer, 0, Math.min(buffer.length, readSize - totalBytesRead))) != -1) {
            baoS.write(buffer, 0, bytesRead);
            totalBytesRead += bytesRead;
        }

        if (totalBytesRead < readSize) {
            baoS.close();
            throw new IOException(TAG + " :tcp have disconnect...");
        }

        byte[] result = baoS.toByteArray();
        baoS.close();
        return result;
    }

    /**
     * byte数组中取int数值，本方法适用于(低位在前，高位在后)的顺序，和和intToBytes（）配套使用
     *
     * @param src byte数组
     * @return int数值
     */
    public static int bytesToInt(byte[] src) {
        int value;
        value = (int) ((src[0] & 0xFF)
                | ((src[1] & 0xFF) << 8)
                | ((src[2] & 0xFF) << 16)
                | ((src[3] & 0xFF) << 24));
        return value;
    }
}
